package com.dd.cloud.common.annotate.validation.impl;

import com.dd.cloud.common.annotate.validation.Ware;
import com.dd.cloud.common.constants.RegularConstants;
import com.dd.cloud.common.utils.RegexUtils;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.constraintvalidation.HibernateConstraintValidatorContext;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * 入库数量验证实现类
 *
 * @author zk
 */
public class WareValidation implements ConstraintValidator<Ware, Object> {
    private Ware ware;

    @Override
    public void initialize(Ware wareVal) {
        ware = wareVal;
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        String ph = (String) value;
        if (!ware.required() && StringUtils.isBlank(ph)) {
            return true;
        }
        if (ware.required() && StringUtils.isBlank(ph)) {
            return false;
        }
        //如果设置的返回的消息参数信息,则替换参数
        if (!StringUtils.isBlank(ware.begin())){
            context.unwrap( HibernateConstraintValidatorContext.class ).addMessageParameter( "begin", ware.begin() );
        }
        return RegexUtils.regCheck(ph, RegularConstants.WARE_REGEXP);
    }
}
